import React, { PureComponent } from 'react';
import { Button, Select } from 'antd';
import PropTypes from 'prop-types';
import moment from 'moment';
import Month from './components/month';
import Year from './components/year';
import styles from './index.less';

const ButtonGroup = Button.Group;
const Option = Select.Option;

// 时间比较 moment的时间带有小时分钟秒等，需要格式化成String再比较，再日后面的单位统一起来
// type可以输入"<","==",">"，分别代表是isBefore,isSame,isAfter,默认是小于
function compareTime(dateOne, dateTwo, type){
  const stringOne = moment(dateOne).format('YYYY-MM-DD');
  const stringTwo = moment(dateTwo).format('YYYY-MM-DD');
  switch(type){
    case '==':
      return moment(stringOne).isSame(moment(stringTwo));
    case '>':
      return moment(stringOne) > moment(stringTwo);
    case '<':
      return moment(stringOne) < moment(stringTwo);
    default:
      return moment(stringOne) < moment(stringTwo);
  }
}
class Calendar extends PureComponent {
  constructor(props){
    super(props);
    this.state = {
      value: this.props.value,
      showPanel: this.props.mode,
      today: moment(),
      onSelect: undefined,
    }
  }
  // 默认date单元格渲染（monthPanel）
   _renderDateItem = (date) => {
    const { disabledDate } = this.props;
    const { value, today, onSelect } = this.state;
    switch (true){
      // 当前月之前的日期的渲染
      case date < value.startOf('month'):
        return(
          <div className='calendar-month-dateValue calendar-month-dateValue-disCurr'>{date.date()}</div>
        );
      // 当前月之后的日期的渲染
      case date > value.endOf('month'):
        return(
          <div className='calendar-month-dateValue calendar-month-dateValue-disCurr'>{date.date()}</div>
        );
      // 禁用日期
      case disabledDate && disabledDate(date):
        return(
          <div className='calendar-month-dateValue calendar-month-disabled'>{date.date()}</div>
        );
      // 今天 + 被选中
      case onSelect && compareTime(date, onSelect, '==') && compareTime(date, today, '==') :
        return(
          <div>
            <div
              className='calendar-month-dateValue calendar-month-dateValue-selected calendar-month-dateValue-today'
            >
              {date.date()}
            </div>
          </div>
        );
      // 今天日期的渲染
      case compareTime(date, today, '=='):
        return(
          <div>
            <div
              onClick={ () => this.setState({onSelect: moment(date)}, () => {
                this.props.onChange ? this.props.onChange(this.state.onSelect) : null;
              })}
              className='calendar-month-dateValue calendar-month-dateValue-today'
            >
              {date.date()}
            </div>
          </div>
        );
      // 被选中的日期的渲染
      case onSelect && compareTime(date, onSelect, '==') :
        return(
          <div>
            <div
              className='calendar-month-dateValue calendar-month-dateValue-selected'
            >
              {date.date()}
            </div>
          </div>
        );
      // 当前月的默认日期的渲染
      default:
        return(
          <div
            onClick={ () => this.setState({onSelect: moment(date)}, () => {
              this.props.onChange ? this.props.onChange(this.state.onSelect) : null;
            })}
            className='calendar-month-dateValue calendar-month-dateValue-curr'
          >
            {date.date()}
          </div>
        )
    }
  };
  // 默认星期头单元格渲染（monthPanel）
  _renderWeekHeadItem = (week) => {
    return(
      <div className='calendar-month-weekHead'>{week}</div>
    )
  };
  // 渲染月面板（monthPanel）
  _renderMonth = () => {
    const { dateFullCellRender } = this.props;
    return(
      <Month
        onSelect={this.state.onSelect}
        renderWeekHead={this._renderWeekHeadItem}
        renderFullDate={dateFullCellRender ? dateFullCellRender : this._renderDateItem}
        month={this.state.value}
      />
    )
  };
  // 默认month单元格渲染(yearPanel)
  _renderMonthItem = (value) => {
    const { value: currDate } = this.state;
    const { month, monthText } = value;
    const du = month - currDate.format('MM');
    switch(true){
      case currDate.format('MM') == month:
        return(
          <div className='calendar-month-dateValue calendar-month-dateValue-selected'>{monthText}</div>
        );
      default:
        return(
          <div
            onClick={() => { this.setState({ value: moment(currDate.add(du, 'month'))})}}
            className='calendar-month-dateValue'>
            {monthText}
          </div>
        );
    }
  };
  // 渲染年面板
  _renderYear = () => {
    return(
      <Year date={this.state.value} renderFullMonth={this._renderMonthItem} className={styles.yearWrapper}/>
    )
  };
  selectYearChange = (selectValue) => {
    const { value } = this.state;
    const formatValue = moment(value.format('YYYY')),
          formatSelectValue = moment(selectValue);
    const du = moment.duration(formatSelectValue - formatValue).as('years');
    this.setState({value: moment(value.add(du, 'year'))});
  };
  selectMonthChange = (selectValue) => {
    const { value } = this.state;
    const formatValue = moment(value.format('MM')),
      formatSelectValue = moment(selectValue),
      du = moment.duration(formatSelectValue - formatValue).as('months');
    this.setState({value: moment(value.add(du, 'month'))});
  };
  render() {
    const { showPanel, value } = this.state;
    return (
      <div>
        <header style={{ overflow: 'hidden', marginBottom: '20px' }}>
          <Select onChange={this.selectYearChange} defaultValue={value.format('YYYY')}>
            { [...new Array(51)].map((value, index) => {
              return (<Option key={`year-${index}`} value={`${1994 + index}`}>{`${1994 + index}`}</Option>)
            })}
          </Select>
          <Select onChange={this.selectMonthChange} defaultValue={value.format('MM')}>
            { [...new Array(12)].map((value, index) => {
              const monthValue = index <= 8 ? `0${index+1}` : `${index + 1}`;
              return (<Option key={`month-${index}`} value={monthValue}>{`${monthValue}月`}</Option>)
            })}
          </Select>
          <ButtonGroup style={{float: 'right'}}>
            <Button
              type={showPanel === 'month' ? 'primary' : null}
              ghost={showPanel === 'month' ? true : null}
              onClick={ () => this.setState({showPanel: 'month'})}
            >
              月
            </Button>
            <Button
              type={showPanel === 'year' ? 'primary' : null}
              ghost={showPanel === 'year' ? true : null}
              style={{ borderLeft: '1px solid #40a9ff'}}
              onClick={ () => this.setState({showPanel: 'year'})}
            >
              年
            </Button>
          </ButtonGroup>
        </header>
        <main>
          {showPanel === 'month' ? this._renderMonth() : this._renderYear()}
        </main>
      </div>
    );
  }
}
Calendar.defaultProps = {
  disabledDate: undefined, // 不可选择的日期
  mode: 'month', // 初始展示的页面
  monthFullCellRender: undefined, //自定义渲染月单元格，返回内容覆盖单元格
  value: moment(), //展示日期 默认展示当前日期
  onChange: undefined, //点击选择日期回调
};
Calendar.prototypes = {

};
export default Calendar;
